package com.tarena.lbs.basic.web.repository;

import com.tarena.lbs.basic.web.source.output.BasicOutputSource;
import com.tarena.lbs.pojo.basic.event.LocationStoreEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Repository;

/**
 * basic业务中 所有需要生产发送消息的方法 都在这个仓储层封装更好
 */
@Repository
@Slf4j
public class EventRepository {
    //把通道来源做注入
    @Autowired
    private BasicOutputSource outputSource;

    public void sendLocationStoreEvent(LocationStoreEvent event) {
        log.info("店铺定位消息:{}",event);
        //1. 封装message
        Message<LocationStoreEvent> message = MessageBuilder.withPayload(event).build();
        //2. 拿到通道
        MessageChannel messageChannel = outputSource.storesLocationOutput();
        //3. 发送消息
        //定义 最大重试次数是3
        int count=0;
        boolean result=false;
        do{
            count++;
            result=messageChannel.send(message);
        }while (!result&&count<3);
        log.info("店铺定位消息发送结束:{}",result);
        //虽然 这里发送消息,如果失败,并不影响业务 但是要体现弱一致性
    }
}
